<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { regYuanToFen, timeFormat, timeStamp, toYuan } from '@/hooks/util'
import * as accountApi from '@/api/account'
import * as fishApi from '@/api/fishGoods'
import * as physicalApi from '@/api/physical'
import { message } from 'ant-design-vue'
import ImgView from './ImgView.vue'
import 'dayjs/locale/zh-cn'
import Modal from '@/components/Modal/index.vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const { ProductRobotList } = storeToRefs(userStore)


const themeStyle = {
  backgroundColor: localStorage.getItem('local_theme') || '#1890FF',
}
const route = useRoute()
const router = useRouter()
const imgViewRef = ref()

const GoodsInfo = ref({})

const myModal = ref()

const columns = [
  // {
  //   title: 'ID',
  //   key: 'id',
  //   width: 200,
  // },
  {
    title: '规格1',
    key: 'optionIndex1',
    width: 200,
  },

  {
    title: '规格2',
    key: 'optionIndex2',
    width: 200,
  },
  {
    title: '售价（元）',
    key: 'sellingPrice',
    width: 200,
  },

  {
    title: '库存（件）',
    key: 'stock',
    width: 200,
  },
  // {
  //   title: '操作',
  //   key: 'action',
  //   width: 150,
  //   fixed: 'right',
  //   align: 'center',
  // },
]
const list1 = ref([])
const key1 = ref("")
const list2 = ref([])
const key2 = ref("")
const list3 = ref([])
const key3 = ref("")
const list4 = ref([])
const key4 = ref("")

//获取闲鱼四级类目
const getCategoryDetail = async (fishCateId: any) => {
  try {
    const { state, data, message: msg } = await physicalApi.getFishCateByFishCateIdList({ fishCateId })
    if (state === 200) {
      if (data.length) {
        list1.value = [data[0]]
        key1.value = data[0].id
        list2.value = [data[1]]
        key2.value = data[1].id
        list3.value = [data[2]]
        key3.value = data[2].id
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error("获取闲鱼类目失败")
  }
}



const showModal = async (info) => {
  console.log('info=', info)

  GoodsInfo.value = info
  //后端未返回 stock字段 前端自加
  if (GoodsInfo.value.productSpecialList.length) {
    GoodsInfo.value.productSpecialList.forEach((item: any) => {
      item.Stock = 0
    })
  }
  await getCategoryDetail(info.fishCateId)

  list4.value = [{ id: info.sendPlaceId, sendPlaceName: info.sendPlaceName }]
  key4.value = info.sendPlaceId
  formState.value.title = info.title
  formState.value.desc = info.desc
  formState.value.originalPrice = toYuan(info.channelPrice)
  formState.value.sellingPrice = toYuan(info.sellingPrice)
  formState.value.transportFee = toYuan(info.postage)
  // formState.value.channelId = info.postage
  // formState.value.spBizType = info.postage
  // formState.value.categoryId =info.postage


  //   formState.value.title = info.title
  //   formState.value.title = info.title

  fileList.value = info.productImages.map((item: any, index) => {
    if (item) {
      return {
        uid: index,
        name: 'image.png',
        status: 'success',
        url: item,
      }
    }
  })

  // myModal.value?.showModal()

  myModal.value.setVisible(true)
}

defineExpose({
  showModal,
})

const emit = defineEmits<{
  refresh: []
}>()

let spinning = ref<boolean>(false)

const labelCol = {
  style: { width: '100px', textAlign: 'center' },
}
const wrapperCol = { span: 10 }

const formRef = ref()
interface formState {
  spBizType?: string
  categoryId?: string
  channelId?: string
  divisionId?: Array<string>
  robotId?: number
  images?: string
  sellingPrice?: number
  originalPrice?: number
  title?: string
  desc?: string
  inventory?: number
  transportFee?: number
  timePush?: any
  categoryTreeTarget?: any
}
const formState = ref<formState>({})

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  spBizType: [{ required: true, message: '请选择行业名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择宝贝类目', trigger: 'blur' }],
  channelId: [{ required: true, message: '请选择宝贝渠道', trigger: 'blur' }],
  divisionId: [{ required: true, message: '请选择地区', trigger: 'blur' }],
  robotId: [{ required: true, message: '请选择店铺', trigger: 'blur' }],
  sellingPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  originalPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  transportFee: [{ required: true, message: '请输入邮费', trigger: 'blur' }],
}

import type { SelectProps } from 'ant-design-vue'

// 行业名称
let spBizType = ref<string>('')
const industryList = ref<SelectProps['options']>([])
const selectIndustry = (selectValue: any) => {
  spBizType.value = selectValue as string
  // getCategoryList(spBizType.value)
}

// 宝贝类目
let categoryId = ref<string>('')
const categoryList = ref<SelectProps['options']>([])
const selectCategory = (selectValue: any) => {
  categoryId.value = selectValue as string
  // getChannelList(categoryId.value)
}

// 宝贝渠道
const channelList = ref<SelectProps['options']>([])

// 地区
let cascaderValue = ref<string[]>([])
const cascaderChange = (value: any[], selectedOptions: any[]) => {
  cascaderValue.value = value
}
const filter = (inputValue: string, path: any[]) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}

const handleSubmit = async () => {
  console.log(fileList.value, 'fileList.value')
  imgList.value = fileList.value.map((item: any) => item.url || item.response.data)

  formRef.value.validate().then(async () => {
    console.log('formState=', formState.value)
    GoodsInfo.value.productSpecialList = GoodsInfo.value.productSpecialList.map(
      (item: any) => {
        return {
          ...item,
          sellerPrice: item.sellingPrice,
          stock: item.Stock
        }
      },
    )
    let param = {
      spBizType: formState.value.spBizType,
      categoryId: formState.value.categoryId,
      robotId: formState.value.robotId,
      sellingPrice: regYuanToFen(Number(formState.value.sellingPrice), 100),
      originalPrice: regYuanToFen(Number(formState.value.originalPrice), 100),
      title: formState.value.title,
      desc: formState.value.desc,
      inventory: formState.value.inventory || 0,
      imgList: imgList.value,
      transportFee: regYuanToFen(formState.value.transportFee, 100),
      specialDTOList: GoodsInfo.value.productSpecialList,
      productId: GoodsInfo.value.id,
      position: GoodsInfo.value.position,
      divisionId: GoodsInfo.value.sendPlaceId,
      fishCateId: GoodsInfo.value.fishCateId,
      fineness: GoodsInfo.value.fineness

    }
    try {
      let { state, message: msg } = await physicalApi.putawayProducts(param)
      if (state === 200) {
        message.success('发布成功')
        // myModal.value.cancelModal()
        myModal.value.setVisible(false)
        setTimeout(() => {
          emit('refresh')
        }, 1000)
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    spinning.value = false
  })
}

// 获取闲鱼店铺
const robatList = ref([])

const handleChangeRadio = (e: any) => {
  formState.value.robotId = e.target.value
}
const getRobatList = async () => {
  const params = { currentPage: 1, pageSize: 100 }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 宝贝图片
const imgList = ref<Array<string>>([
  // 'http://img.alicdn.com/bao/uploaded/i3/O1CN01oxEg4c1vLxY6mSogr_!!3-fleamarket.bmp',
])
interface FileItem {
  uid: string
  name?: string
  status?: string
}
const fileList = ref<FileItem[]>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  return true
}

const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', '1')
  fetch(action, {
    headers: {
      // 'User-Token': userStore.token,
      'User-Token': localStorage.getItem('token') as any,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(result => {
      onSuccess(result, file)
      if (result && result.data != null) {
        imgList.value.push(result.data)
      } else {
        message.error('图片太大，上传失败了!')
        fileList.value.pop()
      }
    })
    .catch(error => {
      message.error('图片太大，上传失败了')
      onError(error)
    })
}

// 预览图片

const handlePreview = async (file: UploadProps['fileList'][number]) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

// 删除图片
const handleRemove = (file: any) => {
  if (file.status != 'error') {
    imgList.value = imgList.value.filter(item => item != file.response.data)
  }
}

interface FileInfo {
  file: FileItem
  fileList: FileItem[]
}
const handleChange = ({ fileList: newFileList }: FileInfo) => {
  fileList.value = newFileList.map((item: any) => {
    if (item.response && item.response.result == false) {
      return {
        uid: '-5',
        name: 'image.png',
        status: 'error',
      }
    } else {
      return item
    }
  })
}

let imgUploadUrl = ref('')
onMounted(() => {
  // 回显
  formState.value.categoryTreeTarget = [
    18,
    '91cb2286b4bd6d5b22b3139b32ea0556',
    'a5fe2de42b13cd9aac1a13d97f8e7bd4',
    '65f5bdcd031bf26d267e0a01017d9f44',
  ]
  // console.log('闲管家全行业类目树categoryTreeOption=', categoryTreeOption)

  imgUploadUrl.value = `${localStorage.getItem('baseUrl')}/platform/wechatReply/uploadToAliOss`
  // getIndustryList()
  // getRobatList()
})

import type { ShowSearchType } from 'ant-design-vue/es/cascader'
const categoryTreeFilter: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}

const changeTree = (val: any, option: any) => {
  console.log('val=', val)
  console.log('option=', option)
}

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

const isDisabled=(item:any)=> {
  return !item.addressCompleteState || !item.authState || !item.fishAuthState;
}
const getDisabledTooltip = (item: any)=> {
   return item.errorMessage;
}
</script>

<template>
  <Modal ref="myModal" title="发布宝贝" :footer="null" :width="900" :height="500">
    <template #contentValue>
      <a-spin tip="Loading..." :spinning="spinning">
        <a-form style="height: 500px; overflow-y: scroll" ref="formRef" :rules="rules" :model="formState"
          :label-col="labelCol" :wrapper-col="wrapperCol">
          <!-- <a-alert description="提醒：由于当前商品发布功能正在调整更新，无法设置不同品类的的属性信息，推荐使用闲鱼app发布商品，发布后选择闲鱼账号，点击“同步当前闲鱼账号宝贝”" type="info"
            banner style="margin-bottom: 10px; padding: 10px" /> -->
          <div style="margin-bottom: 20px">
            <span class="titleFlag" :style="themeStyle"></span>
            <span class="title">基本信息</span>
          </div>
          <a-form-item label="行业名称" name="key1">
            <!-- <a-input :disabled="true" v-model:value="" /> -->
            <a-select v-model:value="key1" @change="selectIndustry" :disabled="true" placeholder="行业名称">
              <a-select-option v-for="(item, index) in list1" :key="index" :value="item.id">
                {{ item.channelCatName }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="宝贝类目" name="key2">
            <a-select v-model:value="key2" @change="selectCategory" :disabled="true" placeholder="宝贝类目">
              <a-select-option v-for="(item, index) in list2" :key="index" :value="item.id">
                {{ item.channelCatName }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="宝贝渠道" name="key3">
            <a-select v-model:value="key3" placeholder="宝贝渠道" :disabled="true">
              <a-select-option v-for="(item, index) in list3" :key="index" :value="item.id">
                {{ item.channelCatName }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="地区" name="key4">
            <!-- <a-cascader v-model:value="formState.divisionId" :options="cascader" :show-search="{ filter }"
              @change="cascaderChange" placeholder="地区" /> -->
            <a-select v-model:value="key4" placeholder="地区" :disabled="true">
              <a-select-option v-for="(item, index) in list4" :key="index" :value="item.id">
                {{ item.sendPlaceName }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <div style="margin-bottom: 20px">
            <span class="titleFlag" :style="themeStyle"></span>
            <span class="title">发布的闲鱼店铺</span>
          </div>

          <a-form-item label="闲鱼店铺" name="robotId">
            <!-- <a-radio-group v-model:value="formState.robotId" :options="ProductRobotList" @change="handleChangeRadio"
              class="selectShop" /> -->

            <a-radio-group v-model:value="formState.robotId">
              <template v-for="(item, index) in ProductRobotList" :key="index">
                <a-tooltip v-if="isDisabled(item)" placement="top" :title="getDisabledTooltip(item)">
                  <a-radio :value="item.value" disabled>
                    {{ item.label }}
                  </a-radio>
                </a-tooltip>
                <a-radio v-else :value="item.value">
                  {{ item.label }}
                </a-radio>
              </template>
            </a-radio-group>
          </a-form-item>

          <div style="margin-bottom: 20px">
            <span class="titleFlag" :style="themeStyle"></span>
            <span class="title">宝贝信息</span>
          </div>

          <!-- 
            action="http://ticket-expert-api.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
            action="http://k8s-cluster.liangpiaovip.com:30080/ticket-expert/platform/wechatReply/uploadToAliOss"
           -->
          <a-form-item has-feedback name="images" label="宝贝图片">
            <a-upload :multiple="true" list-type="picture-card" :action="imgUploadUrl" style="z-index: 99999!important;"
              :show-upload-list="{ showRemoveIcon: true }" :beforeUpload="handleBeforeUpload"
              :customRequest="customRequest" @preview="handlePreview" @remove="handleRemove" @change="handleChange"
              :file-list="fileList">
              <upload-outlined></upload-outlined>
              上传图片
            </a-upload>
          </a-form-item>

          <a-form-item label="宝贝标题" name="title">
            <a-input v-model:value="formState.title"></a-input>
          </a-form-item>

          <a-form-item label="描述" name="desc">
            <a-textarea v-model:value="formState.desc" style="width: 500px;" allow-clear :rows="8"></a-textarea>
          </a-form-item>

          <a-form-item has-feedback label="售价" name="sellingPrice">
            <a-input-number v-model:value="formState.sellingPrice" :disabled="true" style="width: 70%"></a-input-number>
          </a-form-item>

          <a-form-item has-feedback label="原价" name="originalPrice">
            <a-input-number v-model:value="formState.originalPrice" :disabled="true"
              style="width: 70%"></a-input-number>
          </a-form-item>

          <a-form-item has-feedback label="库存" name="inventory1" v-if="GoodsInfo?.productSpecialList?.length > 0">
            <a-table :columns="columns" :dataSource="GoodsInfo?.productSpecialList" :pagination="false">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'optionIndex1'">
                  <div style="width: 150px">{{ record.masterAttrValue }}</div>
                </template>
                <template v-if="column.key === 'optionIndex2'">
                  <div style="width: 150px">{{ record.slaveAttrValue }}</div>
                </template>

                <template v-if="column.key === 'sellingPrice'">
                  <div style="width: 150px">{{ toYuan(record.sellingPrice) }}</div>
                </template>
                <template v-if="column.key === 'stock'">
                  <a-input-number v-model:value="record.Stock" :min="0" :max="record.stock"
                    style="width: 120px"></a-input-number>
                  <div style="margin-top: 10px;color: #999;">库存最多 {{ record.stock }}</div>
                </template>
              </template>
            </a-table>
          </a-form-item>

          <a-form-item has-feedback label="库存" name="inventory" v-else>
            <template #help>
              <div>如您店铺未开通鱼小铺，只能设置库存为1，否则会上品失败</div>
              <div>库存最多可写 {{ GoodsInfo.stock }}</div>

            </template>
            <a-input-number :min="1" :max="GoodsInfo.stock" v-model:value="formState.inventory"
              style="width: 70%"></a-input-number>
          </a-form-item>
          <a-form-item has-feedback label="邮费" name="transportFee">
            <a-input-number v-model:value="formState.transportFee" :disabled="true" style="width: 70%"></a-input-number>
          </a-form-item>

          <!-- 定时发布 -->
          <!-- <a-form-item has-feedback label="定时发布" name="timePush">
            <a-date-picker v-model:value="formState.timePush" showTime :locale="locale" />
          </a-form-item> -->
          <!-- 定时发布 -->
        </a-form>
        <div style="
            border-top: 1px solid #f0f0f0;
            text-align: right;
            padding-top: 10px;
            padding-right: 10px;
          ">
          <a-button @click="() => myModal.setVisible(false)" style="margin-right: 10px">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </div>
      </a-spin>
    </template>
  </Modal>
  <a-modal :open="previewVisible" title="图片" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<style scoped lang="less">
.titleFlag {
  display: inline-block;
  width: 4px;
  height: 16px;
  margin-right: 4px;
  // background-color: #7417be;
  border-radius: 2px;
}

.ant-image-preview {
  z-index: 9999 !important;
  /* 确保层级最高 */
}

.ant-upload-list-picture-card .ant-image-preview {
  z-index: 9999 !important;
}

.title {
  font-weight: bold;
  font-size: 16px;
}

.shop {
  display: inline-block;
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
  margin-bottom: 5px;
}

/deep/ .ant-checkbox-group-item {
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
  margin-bottom: 5px;
}

/deep/ .ant-checkbox-inner,
.ant-checkbox-input {
  border-radius: 50%;
}

/deep/ .ant-upload-list {
  width: 660px;
  font-feature-settings: 'tnum';
  box-sizing: border-box;
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5715;
  list-style: none;
  margin: 0;
  padding: 0;
}
</style>
